package com.shqcjd.preinstallglass.ui.activity.remote;

import android.content.Context;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.open.androidtvwidget.bridge.RecyclerViewBridge;
import com.open.androidtvwidget.leanback.adapter.GeneralAdapter;
import com.open.androidtvwidget.leanback.recycle.GridLayoutManagerTV;
import com.open.androidtvwidget.leanback.recycle.RecyclerViewTV;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.pojo.FileBean;
import com.shqcjd.preinstallglass.ui.adapter.GuideFileListAdapter;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.util.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 文件列表
 */
public class FileListActivity extends BaseActivity {
    @BindView(R.id.rv_file_list)
    RecyclerViewTV rv_file_list;
    @BindView(R.id.ib_back)
    Button ibBack;
    private GuideFileListAdapter guideFileListAdapter;
    private AgoraAPIOnlySignal mAgoraAPI;
    private String channelID;
    private Context mContext;
    private List<FileBean> mList = new ArrayList<>();

    @BindView(R.id.mainUpView1)
    MainUpView mainUpView1;
    private RecyclerViewBridge mRecyclerViewBridge;
    private View oldView;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_file_list;
    }

    @Override
    public void initView() {
        mContext = this;
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        channelID = getIntent().getStringExtra("channelID");

        initRecycleView();
        mainUpView1.setEffectBridge(new RecyclerViewBridge());
        mRecyclerViewBridge = (RecyclerViewBridge) mainUpView1.getEffectBridge();
        mRecyclerViewBridge.setUpRectResource(R.drawable.test_rectangle);
//        RectF receF = new RectF(0, 0,
//                0, 0);
//        mRecyclerViewBridge.setDrawUpRectPadding(receF);
        initAdapter();

    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            if(rv_file_list.getChildCount()>0){
                RelativeLayout rl = rv_file_list.getChildAt(0).findViewById(R.id.rl_item);
                rl.requestFocus();
            }
        }
    };
    Handler h = new Handler();


    private void initRecycleView() {
        rv_file_list.setFocusable(false);
        rv_file_list.setOnItemListener(new RecyclerViewTV.OnItemListener() {
            @Override
            public void onItemPreSelected(RecyclerViewTV parent, View itemView, int position) {
                // 传入 itemView也可以, 自己保存的 oldView也可以.
                mRecyclerViewBridge.setUnFocusView(itemView);
            }

            @Override
            public void onItemSelected(RecyclerViewTV parent, View itemView, int position) {
                mRecyclerViewBridge.setFocusView(itemView, 1.0f);
                oldView = itemView;
            }

            /**
             * 这里是调整开头和结尾的移动边框.
             */
            @Override
            public void onReviseFocusFollow(RecyclerViewTV parent, View itemView, int position) {
                mRecyclerViewBridge.setFocusView(itemView, 1.0f);
                oldView = itemView;
            }
        });
//        rv_file_list.setOnItemClickListener(new RecyclerViewTV.OnItemClickListener() {
//            @Override
//            public void onItemClick(RecyclerViewTV parent, View itemView, int position) {
//                // 测试.
//                mRecyclerViewBridge.setFocusView(itemView, oldView, 1.0f);
//                oldView = itemView;
//                //
////                onViewItemClick(itemView, position);
//            }
//        });
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP);
                simulateKey(keyEvent);

                return true;
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN);
                simulateKey(keyEvent);
                return true;
            }
        }

        return super.dispatchKeyEvent(event);
    }

    public void simulateKey(final KeyEvent keyCode) {

        new Thread() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {
                try {
                    InputMethodManager systemService = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                    systemService.dispatchKeyEventFromInputMethod(getWindow().getDecorView().getRootView(), keyCode);
                } catch (Exception e) {

                }
            }

        }.start();

    }


    private void initAdapter() {
        guideFileListAdapter = new GuideFileListAdapter();
        rv_file_list.setLayoutManager(new LinearLayoutManager(this));
        rv_file_list.setAdapter(guideFileListAdapter);
        guideFileListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FileBean item = (FileBean) adapter.getItem(position);
                Intent intent = new Intent(mContext, UIUtils.previewClass(item.extension));
                intent.putExtra("name", item.filename);
                intent.putExtra("url", item.url);
                startActivity(intent);
            }
        });
    }

    @Override
    protected boolean isAutomaticInitVoice() {
        return false;
    }

    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果----:"+result);
        if(result.equals("返回")){
            finish();
        }else{
            voiceResult(result);
        }
    }

    //"|返回|保存|拍照|输入|删除;"
    private String addVoiceContent(){
        String str = "";
        for(int i=1; i<=mList.size(); i++){
            str = str + "|选择"+i;
        }
        return str + "|返回;";
    }

    private void voiceResult(String result){
        for(int i=1; i<=mList.size(); i++){
            if(result.equals("选择"+i)){
                FileBean item = (FileBean) mList.get(i-1);
                Intent intent = new Intent(mContext, UIUtils.previewClass(item.extension));
                intent.putExtra("name", item.filename);
                intent.putExtra("url", item.url);
                startActivity(intent);
                return;
            }
        }
    }

    @Override
    public void initData() {
        getData();
    }

    private void getData() {
        ApiService.getFileList(channelID)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new Observer<ResponseData<List<FileBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<List<FileBean>> retData) {
                        if (retData.retCode == 10000) {
                            mList = retData.data;
                            guideFileListAdapter.setNewData(mList);
//                            rv_file_list.smoothScrollToPosition(guideFileListAdapter.getItemCount() - 1);
                            getVoiceContent(addVoiceContent());
                            h.postDelayed(r, 500);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        addSignalingCallback();
    }

    private void addSignalingCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            /**
             * 收到频道消息回调
             * @param channelID 频道名
             * @param account 客户端定义的用户账号
             * @param uid 固定填 0
             * @param msg 消息正文
             */
            @Override
            public void onMessageChannelReceive(String channelID, final String account, final int uid, final String msg) {
                super.onMessageChannelReceive(channelID, account, uid, msg);
                Logger.i("接收到频道消息: account:" + account + " uid:" + uid + " msg:" + msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort(mContext, "收到新信息");
                        getData();
                    }
                });
            }

        });
    }


    @OnClick(R.id.ib_back)
    public void onViewClicked() {
        finish();
    }
}
